package com.xiaouyudeguang.common.around;

import com.xiaouyudeguang.common.annotation.ApiMapping;
import com.xiaouyudeguang.common.annotation.ApiResource;
import com.xiaouyudeguang.common.aspect.LogAspect;
import com.xiaouyudeguang.common.config.LogConfig;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Aspect
@Component
@AllArgsConstructor
public class ApiMappingAround extends LogAspect {

    private final HttpServletRequest request;

    private final LogConfig logConfig;

    @Pointcut("execution(* com.*.*.*.resource..*.*(..)) || @annotation(annotation.io.gitee.xiaouyudeguang.common.ApiMapping)")
    public void apiMapping() {
    }

    @SneakyThrows
    @Around("apiMapping()")
    public Object around(ProceedingJoinPoint pjp) {
        if (RequestContextHolder.getRequestAttributes() == null) {
            return pjp.proceed();
        }
        //配置文件关闭了日志输出或不是http请求或请求路径在忽略名单的跳过
        if (!logConfig.getEnabled() || request == null || logConfig.getIgnoreUrls().contains(request.getRequestURI())) {
            return pjp.proceed();
        }
        super.initAspect(pjp);
        //切面到接口代理类的跳过
        if (realClass.isInterface()) {
            return pjp.proceed();
        }
        //类上有@ApiResource注解且关闭了日志输出的跳过
        ApiResource apiResource = realClass.getAnnotation(ApiResource.class);
        if (apiResource != null && apiResource.close()) {
            return pjp.proceed();
        }
        ApiMapping apiMapping = AnnotationUtils.findAnnotation(realMethod, ApiMapping.class);
        if (apiMapping == null) {
            return pjp.proceed();
        }
        return doPrint(pjp, request.getRequestURI(), apiMapping.tags());
    }
}
